<?php

namespace App\Models;

use Laravel\Passport\HasApiTokens; // 新增
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class User
 * @package App\Models
 * @version November 13, 2017, 2:56 pm UTC
 *
 * @property string name
 * @property string password
 * @property string email
 */
class User extends Authenticatable
{
    use SoftDeletes, HasApiTokens, Notifiable, HasRoles; // 增加 HasApiTokens

    public $table = 'users';

    protected $guard_name = 'api';

    public $connection="mysql";

    protected $dates = ['deleted_at'];


    public $fillable = [
        'name',
        'email',
        'true_name',
        'organization_id',
        'phone',
        'flag',
    ];

    public $hidden = [
        'password',
        'remember_token'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'name' => 'string',
        'password' => 'string',
        'email' => 'string'
    ];

    /**
     * 将资源转换成数组。
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray()
    {
        $mergeArray = [
            'organizations'=>[],
        ];

        if(!is_null($this->organization)) {
            $mergeArray['organizations'] = Organization::ancestorsAndSelf($this->organization->id);
        }

        return array_merge(parent::toArray(), $mergeArray);
    }

    /**
     * 密码修改器。
     *
     * @param  string $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }


    /**
     * Return all the permissions the model has via roles.
     */
    public function getParsViaRoles()
    {
        return $this->load('roles', 'roles.parks')
            ->roles->flatMap(function ($role) {
                return $role->parks;
            })->sort()->values();
    }

}
